// axios基础封装
import axios from "axios";
import {showMessage} from '../status/showMessage'
import {ElMessage} from "element-plus";
import router from "@/router";

const request = axios.create({
    //基础路径
    baseURL: 'http://localhost:8080',
    //超时时间
    timeout: 5000
})

//http request 拦截器
request.interceptors.request.use(
    config => {
        // 配置请求头
        /*   config.headers = {
              //'Content-Type':'application/x-www-form-urlencoded',   // 传参方式表单
              'Content-Type': 'application/json;charset=UTF-8'      // 传参方式json
              // 这里自定义配置，这里传的是token
          }; */
        console.log(config.url.split("?")[0])
        const WhiteList = ['api/user/login', '/api/user/register']
        if (!WhiteList.includes(config.url.split("?")[0])) {
            const token = JSON.parse(window.sessionStorage.getItem("user")).token
            config.headers.token = token
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//http response 拦截器
request.interceptors.response.use(
    response => {
        if (response.data.code === 500) {
            window.sessionStorage.removeItem("user")
            ElMessage.error(response.data.message)
            router.push("/login")
            return Promise.reject(response.data);
        }
        return response
    },
    error => {
        const {response} = error;
        if (response) {
            // 请求已发出，但是不在2xx的范围
            console.log(response.status)
            const message = showMessage(response.status);           // 传入响应码，匹配响应码对应信息
            ElMessage.error(message)
            return Promise.reject(response.data);
        } else {
            ElMessage.warning('网络连接异常,请稍后再试!');
        }
    }
);
export default request
